package com.spring.shiro.service;

import com.spring.shiro.entity.JobLog;
import com.spring.shiro.mapper.JobLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class JobLogService {

    @Autowired
    private JobLogMapper jobLogMapper;

    @Transactional
    public void saveJobLog(JobLog log) {
        jobLogMapper.insert(log);
    }

    public List<JobLog> findAllJobLogs(JobLog jobLog) {
        try {
            Example example = new Example(JobLog.class);
            Example.Criteria criteria = example.createCriteria();
            if (StringUtils.isNotBlank(jobLog.getBeanName())) {
                criteria.andCondition("bean_name=", jobLog.getBeanName());
            }
            if (StringUtils.isNotBlank(jobLog.getMethodName())) {
                criteria.andCondition("method_name=", jobLog.getMethodName());
            }
            if (StringUtils.isNotBlank(jobLog.getStatus())) {
                criteria.andCondition("status=", Long.valueOf(jobLog.getStatus()));
            }
            example.setOrderByClause("log_id desc");
            return jobLogMapper.selectByExample(example);
        } catch (Exception e) {
            log.error("获取调度日志信息失败", e);
            return new ArrayList<>();
        }
    }

    @Transactional
    public void deleteBatch(String ids) {
        List<String> list = Arrays.asList(ids.split(","));

        Example example = new Example(JobLog.class);
        example.createCriteria().andIn("logId", list);

        jobLogMapper.deleteByExample(example);
    }
}
